package com.jugheadzhou.core.message.rabbitmq.producer;

import com.jugheadzhou.core.message.IMessage;
import com.jugheadzhou.core.message.rabbitmq.producer.meta.RabbitMeta;
import com.jugheadzhou.core.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import java.util.UUID;

/**
 * Rabbitmq 发送
 *
 * @author jugheadzhou
 * @date 2021-12-02
 */
@Slf4j
public class RabbitSender {

    private RabbitTemplate rabbitTemplate;

    public RabbitSender(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    /**
     * 消息发送
     *
     * @param rabbitMeta
     * @param data
     * @return
     */
    public boolean send(RabbitMeta rabbitMeta, Object data) {
        try {
            // 用于回调的内容
            CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
            // 发送
            rabbitTemplate.convertAndSend(rabbitMeta.getExchange(), rabbitMeta.getRoutingKey(), wrapperRabbitMessage(data), correlationData);
            return true;
        } catch (Exception e) {
            log.error("发送rabbitmq消息发送了未知异常：", e);
        }
        return false;
    }

    /**
     * 标准化转换消息体
     *
     * @param data 业务数据
     */
    public static IMessage wrapperRabbitMessage(Object data) {
        IMessage msg = IMessage.builder()
                .key(UUID.randomUUID().toString())
                .timestamp(System.currentTimeMillis())
                .data(JsonUtil.object2String(data))
                .build();
        return msg;
    }
}
